package com.hezhiqin.mvcframwork.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hezhiqin.hand.HandlerMapping;
import com.hezhiqin.mvcframework.annotation.HZQAutowired;
import com.hezhiqin.mvcframework.annotation.HZQController;
import com.hezhiqin.mvcframework.annotation.HZQRequestMapping;
import com.hezhiqin.mvcframework.annotation.HZQRequestParam;
import com.hezhiqin.mvcframework.annotation.HZQService;

/**
 * @author Administrator
 *所有的核心逻辑卸载init方法中
 */
public class HZQDispathcherServlet  extends HttpServlet{
	
	//新建一个“容器”
	private Map<String,Object> ioc = new HashMap<String, Object>();

	//保存 application.properties 配置文件中的内容
	private Properties contextConfig = new Properties();
	
	//保存扫描的所有的类名
	private List<String> classNames = new ArrayList<String>();

	//保存 url 和 Method 的对应关系
//	private Map<String,Method> handlerMapping = new HashMap<String,Method>();
	
	private List<HandlerMapping> handlerMapping = new ArrayList<HandlerMapping>();



	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req,resp);
	}

	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			doDispatch(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));
		}

	}



	private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		 HandlerMapping handler = getHandler(req);
		 if (handler==null) {
			 resp.getWriter().write("404 Not Found!!!");
			 return;

		}
		 
		//获得方法的形参列表
		 Class<?> [] paramTypes = handler.getParamTypes();
		 
		 Object [] paramValues = new Object[paramTypes.length];

		 Map<String,String[]> params = req.getParameterMap();
		 
		 for (Map.Entry<String, String[]> parm : params.entrySet()) {
			 
			 String value = Arrays.toString(parm.getValue()).replaceAll("\\[|\\]","")
					 .replaceAll("\\s",",");
			 if(!handler.paramIndexMapping.containsKey(parm.getKey())){continue;}
			 int index = handler.paramIndexMapping.get(parm.getKey());
			 paramValues[index] = convert(paramTypes[index],value);


			 
		 }
		 
		 if(handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())) {
			 int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
			 paramValues[reqIndex] = req;
		 }



		 if(handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())) {
			 int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
			 paramValues[respIndex] = resp;
		 }
		 
		 Object returnValue = handler.method.invoke(handler.controller,paramValues);
		 
		 if(returnValue == null || returnValue instanceof Void){ return; }
		 
		 resp.getWriter().write(returnValue.toString());




		
	}



	private HandlerMapping getHandler(HttpServletRequest req) {
		if(handlerMapping.isEmpty()){ return null; }
		String url = req.getRequestURI();
		String contextPath = req.getContextPath();
		url = url.replace(contextPath, "").replaceAll("/+", "/");
		System.out.println("我草拟大爷"+url);
		for (HandlerMapping  handler : handlerMapping) {
			Matcher matcher = handler.pattern.matcher(url);
			System.out.println(matcher.matches());
			//如果没有匹配上继续下一个匹配
			if(!matcher.matches()){ continue; }
			return handler;
		}
		return null;
		

	}



	@Override
	public void init(ServletConfig config) throws ServletException {//初始化
		//加载配置文件
		doLoadConfig(config.getInitParameter("contextConfigLocation"));
		
		//2、扫描相关的类
		doScanner(contextConfig.getProperty("scanPackage"));

		//3、初始化扫描到的类，并且将它们放入到 ICO 容器之中
		doInstance();
		
		//4、完成依赖注入
		doAutowired();

		//5、初始化 initHandlerMapping
		initHandlerMapping();

		System.out.println("HZQ Spring framework is init.");
		
		
	}



	private void initHandlerMapping() {
		if(ioc.isEmpty()){ return; }
		for (Entry<String, Object> entry : ioc.entrySet()) {
			Class<?> clazz = entry.getValue().getClass();
			if(!clazz.isAnnotationPresent(HZQController.class)){ continue; }
			String url = "";
			if(clazz.isAnnotationPresent(HZQRequestMapping.class)){
				HZQRequestMapping requestMapping = clazz.getAnnotation(HZQRequestMapping.class);
				url = requestMapping.value();
			}

			//获取 Method 的 url 配置
			Method [] methods = clazz.getMethods();

			for (Method method : methods) {

				//没有加 RequestMapping 注解的直接忽略
				if(!method.isAnnotationPresent(HZQRequestMapping.class)){ continue; }
				//映射 URL
				HZQRequestMapping requestMapping = method.getAnnotation(HZQRequestMapping.class);
				String regex = ("/" + url + requestMapping.value()).replaceAll("/+", "/");
				Pattern pattern = Pattern.compile(regex);
				handlerMapping.add(new HandlerMapping(entry.getValue(),method,pattern));
				System.out.println("mapping " + regex + "," + method);

			}



		}


	}



	private void doAutowired() {
		if(ioc.isEmpty()){return;}

		for (Map.Entry<String, Object> entry : ioc.entrySet()) {
			//Declared 所有的，特定的 字段，包括 private/protected/default
			//正常来说，普通的 OOP 编程只能拿到 public 的属性
			Field[] fields = entry.getValue().getClass().getDeclaredFields(); 
			for (Field field : fields) {
				if (!field.isAnnotationPresent(HZQAutowired.class)) {
					continue;
				}
				HZQAutowired autowired = field.getAnnotation(HZQAutowired.class);
				//如果用户没有自定义 beanName，默认就根据类型注入
				//这个地方省去了对类名首字母小写的情况的判断，这个作为课后作业
				//小伙伴们自己去完善
				String beanName = autowired.value().trim();
				if("".equals(beanName.trim())){
					beanName =toLowerFirstCase(field.getType().getSimpleName()) ;
				}
				
				//如果是 public 以外的修饰符，只要加了@Autowired 注解，都要强制赋值
				//反射中叫做暴力访问， 强吻
				field.setAccessible(true);
				try {
					//用反射机制，动态给字段赋值
					field.set(entry.getValue(),ioc.get(beanName));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}

			}
		}

	}



	private void doInstance() {
		if (classNames.isEmpty()) {
			return;
		}
		try {
			for (String className : classNames) {
				
				Class<?> clazz = Class.forName(className);//从Lits中存的类的地址获取内存中对应的Class
				//什么样的类才需要初始化呢？
				//加了注解的类，才初始化，怎么判断？
				//为了简化代码逻辑，主要体会设计思想，只举例 @Controller 和@Service,
				// @Componment...就不一举例了
				if (clazz.isAnnotationPresent(HZQController.class)) {//如果是@HZQControlle
					Object instance = clazz.newInstance();
					//Spring 默认类名首字母小写
					String beanName = toLowerFirstCase(clazz.getSimpleName());
					ioc.put(beanName,instance);//加载到容器中

				}else if (clazz.isAnnotationPresent(HZQService.class)) {
					//1、自定义的 beanName
					HZQService service = clazz.getAnnotation(HZQService.class);
					String beanName = service.value();
					if("".equals(beanName.trim())){
						beanName = toLowerFirstCase(clazz.getSimpleName());
					}
					Object instance = clazz.newInstance();
					ioc.put(beanName,instance);
					//3、根据类型自动赋值,投机取巧的方式
					for (Class<?> i  : clazz.getInterfaces()) {
						if (ioc.containsKey(i.getSimpleName())) {
							throw new Exception("The “" + i.getName() + "” is exists!!");
						}
						ioc.put(toLowerFirstCase(i.getSimpleName()), instance);
					}
				}else {
					continue;
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	private void doLoadConfig(String initParameter) {
		//直接从类路径下找到 Spring 主配置文件所在的路径
		//并且将其读取出来放到 Properties 对象中
		//相对于 scanPackage=com.hezhiqin 从文件中保存到了内存中
		InputStream fis = this.getClass().getClassLoader().getResourceAsStream(initParameter);
		try {
			contextConfig.load(fis);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}



	/**
	 * @param scanPackage
	 * 扫描配置的路径，将所有相关的类放入容器中
	 */
	private void doScanner(String scanPackage) {
		//scanPackage = com.hezhiqin ，存储的是包路径
		//转换为文件路径，实际上就是把.替换为/就 OK 了
		URL url = this.getClass().getClassLoader().getResource("/" +
				scanPackage.replaceAll("\\.","/"));//将扫描的包的.换成/
		File classDir = new File(url.getFile());
		for (File file : classDir.listFiles()) {
			if (file.isDirectory()) {//如果是一个文件
				doScanner(scanPackage + "." +file.getName());
			}else {
				if(!file.getName().endsWith(".class")){continue;}//不是一个class文件则跳过
				String clazzName = (scanPackage + "." + file.getName().replace(".class",""));//获取classpath
//				ioc.put(clazzName,null);//写入Key
//				System.out.println("ioc"+ioc);

				classNames.add(clazzName);//V2存到LIST中

			}
		}


	}
	
	
	private String toLowerFirstCase(String simpleName) {
		char [] chars = simpleName.toCharArray();
		//之所以加，是因为大小写字母的 ASCII 码相差 32，
		// 而且大写字母的 ASCII 码要小于小写字母的 ASCII 码
		//在 Java 中，对 char 做算学运算，实际上就是对 ASCII 码做算学运算
		if (isUpperCase(chars[0])) {
			chars[0] += 32;
		} 
		return String.valueOf(chars);

	}
	
	

	/*
	 * 是否是大写
	 */
	public boolean isUpperCase(char c) {
	    return c >=65 && c <= 90;
	}
	
	
	private Object convert(Class<?> type,String value){
		if(Integer.class == type){
			return Integer.valueOf(value);
		}
		return value;
	}

	
}
